#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/* Example version string:
 * =>"Linux version 3.2.0-g5908eb9-dirty (root@develop) (gcc version 4.5.3 20110311 (prerelease) (GCC) ) #7 Tue Apr 14 12:35:55 CST 2015\n"
 * =>"Linux version 4.4.0-53-generic (buildd@lcy01-20) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4) ) #74-Ubuntu SMP Fri Dec 2 15:58:04 UTC 2016\n"
 */

/*
 * Gets the position of the nth 'char'.
 * if @n > 0, search 'char' from @str's left to right
 * else from right to left.
 */
#define get_head(origin, len, dir) ((dir) >= 0? (origin): (origin) + (len) -1)
#define get_tail(origin, len, dir) ((dir) >= 0? (origin) + (len) -1: (origin))
static const char *get_nth_char_pos(const char *str, int len, char ch, int n)
{
	int step = ( n >= 0? 1: -1);
	const char *head = get_head(str, len, n);
	const char *tail = get_tail(str, len, n);

	if(n < 0) n = -n;
	if(!str || !len || !n) return NULL;

	for(; head != tail; head += step) {
		if(*head == ch) n--;
		if(n == 0) return head;
	}

	return NULL;
}

static void replace_with(char *str, int len, char replace, char with)
{
	int i = 0;

	for(; i < len; i++) {
		if(str[i] == replace)
			str[i] = with;
	}
}

/*
 * Read version from kernel
 */
static int read_version(char *buf, int len)
{
	int fd, bytes, count = 0;

	if( (fd = open("/proc/version", O_RDONLY)) < 0) return 0;
	do {
		bytes = read(fd, buf + count, len - count);
		count += bytes;
	}while(bytes > 0);

	/* the last one is '\n', remove */
	buf[count - 1] = '\0';

	return count - 1;
}

int main(void)
{
	char ver[256];
	int len, i = 0;
	char *start, *list[5];

	if(!(len = read_version(ver, sizeof(ver)))) {
		fprintf(stderr, "Can't get version information\n");
		exit(-1);
	}
	                                                         /*  | list[0]                             */
	                                                         /*  V                                     */
	start = (char *)get_nth_char_pos(ver, len, ' ', -5) + 1; /* "Apr[1]14[2]12:35:55[3]CST[4]2015[\0]" */
	len = strlen(start);
	replace_with(start, len, ' ', '\0'); /* replace space with null */

	list[0] = start;
	for(i = 1; i < 5; i++) {
		list[i] =(char *)get_nth_char_pos(start, len, '\0', i) + 1;
	}


	printf("Year:%s Month:%s Day:%s\n", list[4], list[0], list[1]);
	return 0;
}
